package com.mnxiaotu.common.security;

import com.github.pagehelper.util.StringUtil;
import com.mnxiaotu.common.Context.MyApplicationContext;
import com.mnxiaotu.common.constant.JwtConstant;
import com.mnxiaotu.common.vo.CheckResult;
import com.mnxiaotu.entity.User;
import com.mnxiaotu.service.UserService;
import com.mnxiaotu.util.JwtUtils;
import com.mnxiaotu.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author 86182
 */

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private UserService userService= MyApplicationContext.getBean(UserService.class);

    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService =MyApplicationContext.getBean(MyUserDetailsServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil= MyApplicationContext.getBean(RedisUtil.class);

    private static final String URL_WHITELIST[] ={
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**"
    } ;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        System.out.println("请求url:"+request.getRequestURI());
        // 如果token是空 或者 url在白名单里，则放行
        if(StringUtil.isEmpty(token) || new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())){
            chain.doFilter(request,response);
            return;
        }
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if(!checkResult.isSuccess()){
            switch (checkResult.getErrCode()){
                case JwtConstant.JWT_ERRCODE_NULL:throw new JwtException("Token不存在");
                case JwtConstant.JWT_ERRCODE_FAIL:throw new JwtException("Token验证不通过");
                case JwtConstant.JWT_ERRCODE_EXPIRE:throw new JwtException("Token过期");
            }
        }

        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();

        // 判断redis中是否存在jwt
        Object res = redisUtil.get(username + ":", "token");
        if(ObjectUtils.isEmpty(res)) {
            throw new JwtException("Token 已过期");
        }

        User user = userService.getByUsername(username);

        // 根据查询的用户信息封装成一个Authentication用户认证信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(username,null,myUserDetailsService.getUserAuthority(user.getId()));
        // 将得到的用户认证信息填入到上下文中
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        // 放行
        chain.doFilter(request,response);
    }
}

